<?php
namespace addons\Car\common\models;
use Yii;
use common\helpers\ArrayHelper;
use yii\helpers\Json;


class Car extends \common\models\base\BaseModel
{


    /**
     * {@inheritdoc}
     */
    public static function tableName()
    {
        return '{{%addon_car}}';
    }

    /**
     * {@inheritdoc}
     */
    public function rules()
    {
        return [
            [['title', 'cate_id','plate_number','vehicle_license','mileage','state'], 'required'],
            [['cate_id','mileage','state','status'], 'integer'],
            [['title','plate_number','vehicle_license'], 'string','max' => 32],
            [['mark','picture'], 'string','max' => 255],
            [['insurance','inspection','created_at', 'updated_at','covers'], 'safe'],

        ];
    }

    /**
     * {@inheritdoc}
     */
    public function attributeLabels()
    {
        return [
            'id' => 'ID',
            'member_id' => '用户',
            'cate_id' => '车型',
            'title' => '名称',
            'plate_number' => '车牌号',
            'vehicle_license' => '行驶证',
            'insurance' => '保险到期',
            'inspection' => '年检到期',
            'mileage' => '里程(KM)',
            'covers'=> '车辆照片',
            'mark' => '备注',
            'state' => '车辆状态',
            'status' => '状态',
            'created_at' => '创建时间',
            'updated_at' => '更新时间',
        ];
    }
    public function getCate()
    {
        return $this->hasOne(CarCate::class, ['id' => 'cate_id']);
    }
    public static function getDropDown()
    {
        $models = self::find()
            ->select(['id','title'])
            ->where(['state' => \addons\Car\common\enums\CarStateEnum::Free])
            ->orderBy('id asc,title asc')
            ->asArray()
            ->all();
        return ArrayHelper::map($models, 'id', 'title');
    }
    public function beforeSave($insert)
    {
        $this->merchant_id = Yii::$app->user->identity->merchant_id;
        // 更新系统主图
        $covers = Json::decode($this->covers);
        $this->picture = $covers[0] ?? '';
        return parent::beforeSave($insert);
    }
}
